import { _decorator, Component, easing, EventTouch, Input, input, instantiate, Node, Prefab, Tween, tween, Vec3 } from 'cc';
import { GameManager } from './GameManager';
const { ccclass, property } = _decorator;

@ccclass('Bascket')
export class Bascket extends Component {
	private _offset: Vec3 = new Vec3()

	@property
	public minPos = new Vec3()

	@property
	public maxPos = new Vec3()

	private _isDragging: boolean = false

	@property(Prefab)
	public futureWorkLabel: Prefab = null
	@property(Node)
	public restartGameLabel: Node = null

	start() {
		//
		this.scheduleOnce(() => {
			// this.removeEvent();
			let futureWorkLabelNode = instantiate(this.futureWorkLabel)
			futureWorkLabelNode.parent = this.node
			let t1 = tween(futureWorkLabelNode).to(
				1.5,
				{ position: new Vec3(0, 100, 0) },
				{ easing: 'backInOut' }
			)
			t1.start()
			let t2 = tween(this.node).to(
				1.5,
				{ position: new Vec3(0, 300, 0) }
				// { easing: 'backInOut' }
			)
			// t2.start();
			t1.call(() => {
                t2.start();
                this.restartGameLabel.active = true;
			}).start()
		}, GameManager.instance.timer)
	}

	protected onLoad(): void {
		this.onEvent()
	}
	private onEvent() {
		input.on(Input.EventType.TOUCH_START, this.onTouchStart, this)
		input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this)
		input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this)
		input.on(Input.EventType.TOUCH_CANCEL, this.onTouchCancel, this)
	}

	onTouchStart(event: EventTouch) {
		let curPos = this.node.position
		let touchPos = event.getUILocation()
		Vec3.subtract(this._offset, new Vec3(touchPos.x, touchPos.y), curPos)
		this._isDragging = true
	}
	onTouchMove(event: EventTouch) {
		if (!this._isDragging) return
		let targetPos = new Vec3()
		let touchPos = event.getUILocation()
		Vec3.subtract(targetPos, new Vec3(touchPos.x, touchPos.y), this._offset)
		targetPos = this.clampPosition(targetPos)
		this.node.setPosition(targetPos)
	}

	clampPosition(curPosition: Vec3): Vec3 {
		const clampX = Math.max(
			this.minPos.x,
			Math.min(this.maxPos.x, curPosition.x)
		)
		const clampY = Math.max(
			this.minPos.y,
			Math.min(this.maxPos.y, curPosition.y)
		)
		return new Vec3(clampX, clampY, curPosition.z)
	}

	onTouchEnd(event: EventTouch) {
		console.log('touch end')
		this._isDragging = false
	}
	onTouchCancel(event: EventTouch) {
		console.log('touch cancel')
		this._isDragging = false
	}

	protected onDestroy(): void {
		this.removeEvent()
	}

	private removeEvent() {
		input.off(Input.EventType.TOUCH_START, this.onTouchStart, this)
		input.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this)
		input.off(Input.EventType.TOUCH_END, this.onTouchEnd, this)
		input.off(Input.EventType.TOUCH_CANCEL, this.onTouchCancel, this)
	}
}


